const express = require("express");
const router = express.Router();
const ctx = require("../../utils/mysql")


//获取首页图片
router.get("/banner",async(req,res) => {
    const sql = `SELECT * FROM banner`
    ctx.query(sql,function(error,results,fields){
        return res.send({
            code:200,
            data:results
        })
    })
})
//删除
router.delete('/banner',async(req,res) => {
    const {id} = req.query
    if(id){ 
        const sql = `DELETE FROM banner WHERE id = ${id}`
        ctx.query(sql, function(error, results,fields){
            console.log(results);
            if(!results){
                return res.send({
                    code:400,
                    message:'删除轮播图失败！'
                })
            }else{
                return res.send({
                    code:200,
                    message:'删除轮播图成功！'
                })
            }
        })
    }else{
        return res.send({
            code:400,
            message:'错误'
        })
    }
})
// 添加
router.post("/banner", async (req, res) => {
    const { carousel } = req.body
    if (carousel) {
        const isExits = `SELECT 1 FROM banner WHERE carousel = '${carousel}'`
        const sql = `INSERT INTO banner(carousel) VALUES ('${carousel}')`
        ctx.query(isExits, function (error, results, fields) {
            console.log(results);
            if (results.length !== 0) {
                return res.send({
                    code: 400,
                    message: '已存在'
                })
            }
            ctx.query(sql, function (error, results, fields) {
                if (!results) {
                    return res.send({
                        code: 500,
                        message: '服务器错误'
                    })
                }
                return res.send({
                    code: 200,
                    message: '添加成功',
                    data: results[0]
                })
            })
        })
    } else {
        return res.send({
            code: 400,
            message: '失败'
        })
    }
});

module.exports = router;